package com.example.demo.controller;


import com.example.demo.model.UserInfo;
import com.example.demo.service.UserService;
import com.example.demo.util.ConstVariable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public boolean login(HttpServletRequest request,String username,String password){
        if(StringUtils.hasLength(username) && StringUtils.hasLength(password)){
            // 参数有效
            UserInfo userInfo = userService.loginByUsername(username);
            if(userInfo != null){
                String dbPassword = userInfo.getPassword();
                if(dbPassword.equals(password)){
                    HttpSession session = request.getSession(true);
                    session.setAttribute(ConstVariable.USER_SEESION_KEY,userInfo);
                    return true;
                }
            }
        }
        return false;
    }

    @RequestMapping("/userInfo")
    public UserInfo userInformation(HttpServletRequest request){
        UserInfo userInfo = null;
        UserInfo userInfo1 = null;
        HttpSession session = request.getSession(false);
        userInfo =(UserInfo) session.getAttribute(ConstVariable.USER_SEESION_KEY);
        if(request.getParameter("blogId")!=null){
            userInfo1 = userService.userInfoByBlogId(Integer.valueOf(request.getParameter("blogId")));
            if(userInfo1.getUserId()==userInfo.getUserId()){
                userInfo.setPassword("1");
                return userInfo;
            }else{
                userInfo1.setPassword("0");
                return userInfo1;
            }
        }
        return userInfo;
    }

    @RequestMapping("/logout")
    public void logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if(session!=null){
            session.removeAttribute(ConstVariable.USER_SEESION_KEY);
        }
    }
}
